package parser;

import java.util.HashMap;
import java.util.Iterator;

import java.io.InputStream;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.xml.sax.SAXException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 *
 * @author Ilio Catallo, Eleonora Ciceri
 * @version: 1.0
 * @see: Parser
 * 
 * Description: The class implements an XML parser
 * 
 * Date: Nov 16, 2011
 */
public class XMLParser extends Parser {
    
    private Document dom;
    
    /**
     * Constructor for the class XMLParser
     * @param attributes 
     */
    public XMLParser() {
        super();
    }

    @Override
    public void parse(InputStream document) {
        
        this.dom = buildDOM(document);
        this.responseAttributes.clear();
        
        // Look for the requested attributes
        NodeList nodes = dom.getElementsByTagName(navigationPath.get(0)); //hack: mettere la nagicazioen dell'intero navigationPath
        
        if (nodes != null && nodes.getLength() > 0) {
            for (int i = 0; i < nodes.getLength(); i++) {
                
                Element elem = (Element)nodes.item(i);
                HashMap<String, String> currAttribute = new HashMap<String, String>();
                Iterator keyIterator = this.attributes.keySet().iterator();
                
                while (keyIterator.hasNext()){
                    String keyName = (String)keyIterator.next();
                    currAttribute.put(keyName, elem.getAttribute(keyName));
                }
                
                responseAttributes.add(currAttribute);
            }
        }
        
    }
    
    private Document buildDOM(InputStream document) {
        // Variables
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        Document dom = null;
        
        try {

            DocumentBuilder db = dbf.newDocumentBuilder();
            dom = db.parse(document);

        }
        catch(ParserConfigurationException pce) {
            pce.printStackTrace();
        }
        catch(SAXException se) {
            se.printStackTrace();
        }
        catch(IOException ioe) {
            ioe.printStackTrace();
        }
        
        return dom;
    }
}
